package com.sunshine.wrongquestionset.activity.exercise

import android.content.Intent
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView

import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.bumptech.glide.Glide
import com.google.android.material.button.MaterialButton

import com.google.android.material.textfield.TextInputEditText

import com.sunshine.wrongquestionset.R
import com.sunshine.wrongquestionset.activity.add_question.AddQuestionActivity
import com.sunshine.wrongquestionset.activity.add_question.AddQuestionExpendActivity
import com.wanglu.photoviewerlibrary.PhotoViewer

import com.zzhoujay.markdown.MarkDown
import com.zzhoujay.richtext.ImageHolder
import com.zzhoujay.richtext.RichText
import com.zzhoujay.richtext.RichType
import com.zzhoujay.richtext.callback.OnImageClickListener

import kotlinx.android.synthetic.main.fragment_exercise.*
import kotlinx.android.synthetic.main.fragment_exercise.textView_title_content
import kotlinx.android.synthetic.main.fragment_home.*

class ExerciseFragment : Fragment() {
    private var positionId: Int = -1
    private var questionId: Int = -1
    private lateinit var viewModel: ExerciseViewModel

    private lateinit var editAnswer: TextInputEditText

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            positionId = it.getInt(ARG_PARAM_POSITION_ID)
            questionId = it.getInt(ARG_PARAM_QUESTION_ID)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_exercise, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        viewModel = ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(requireActivity().application)).get(ExerciseViewModel::class.java)
        viewModel.getQuestion(questionId).observe(viewLifecycleOwner, Observer {
            RichText
                .from("第${positionId}题(${it?.score}分)\n\n${it?.titlePath?.replace("\n", "\n\n")}")
                .type(RichType.markdown)
                .scaleType(ImageHolder.ScaleType.fit_auto)
                .imageClick(object : OnImageClickListener {
                    override fun imageClicked(imageUrls: MutableList<String>?, position: Int) {
                        if (imageUrls.isNullOrEmpty()) return
                        PhotoViewer
                            .setClickSingleImg(imageUrls[position], ImageView(requireContext()))   //因为本框架不参与加载图片，所以还是要写回调方法
                            .setShowImageViewInterface(object : PhotoViewer.ShowImageViewInterface {
                                override fun show(iv: ImageView, url: String) {
                                    Glide.with(iv.context).load(url).into(iv)
                                }
                            })
                            .start(this@ExerciseFragment)
                    }
                })
                .into(textView_title_content)
//            textView_title_content.post {
//                Thread {
//                    val spanned = MarkDown.fromMarkdown("第${positionId}题(${it?.score}分)\n\n${it?.titlePath?.replace("\n", "\n\n")}", { source ->
//                        try {
//                            //主线程执行，效果不是很好
//                            val drawable = Drawable.createFromPath(source)
//                            drawable?.setBounds(0, 0, drawable.intrinsicWidth, drawable.intrinsicHeight)
//                            drawable
//                        }catch (e: Exception) {
//                            //Snackbar.make(add_question_expend_root, getString(R.string.load_image_fail_2), Snackbar.LENGTH_SHORT).show()
//                            null
//                        }
//                    }, textView_title_content)
//
//                    textView_title_content.post {
//                        textView_title_content.text = spanned
//                    }
//                }.start()
//            }
        })

        val expend: MaterialButton = include_answer.findViewById(R.id.imageView_expend)
        editAnswer = include_answer.findViewById(R.id.edit_answer)

        editAnswer.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                val answerPath: String? = s?.let { s.toString() }

                if (answerPath.isNullOrBlank()) {
                    ExerciseActivity.removeAnswer(positionId)
                } else {
                    ExerciseActivity.addAnswer(positionId, questionId, answerPath)
                }

                //通知题目更新
                (requireActivity() as ExerciseActivity).notifyCardFragmentDataSetChanged()
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {

            }

        })

        expend.setOnClickListener {
            val intent = Intent(requireActivity(), AddQuestionExpendActivity::class.java)
            intent.putExtra("type", AddQuestionActivity.TYPE_ANSWER)
            intent.putExtra("text", editAnswer.text?.toString())
            //使用questionId作为tag，可以保证收到的消息唯一
            startActivityForResult(intent, questionId)
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == questionId || resultCode == AddQuestionActivity.TYPE_ANSWER) {
            editAnswer.setText(data?.getStringExtra("text"))
        }
    }

    companion object {
        private const val ARG_PARAM_QUESTION_ID = "question"
        private const val ARG_PARAM_POSITION_ID = "position"
        @JvmStatic
        fun newInstance(positionId: Int, questionId: Int) =
            ExerciseFragment().apply {
                arguments = Bundle().apply {
                    putInt(ARG_PARAM_POSITION_ID, positionId)
                    putInt(ARG_PARAM_QUESTION_ID, questionId)
                }
            }
    }
}